package com.example.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.database.ActiveDbManager;
import com.example.database.DbManager;
import com.example.juyixia.Activity_chatActivity;
import com.example.juyixia.MainActivity;
import com.example.juyixia.Myinfo;
import com.example.juyixia.PendActiveActivity;
import com.example.juyixia.R;
import com.exanple.data.Activeinfo;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 监听是否有活动请求的服务
 * 
 * @author Administrator
 *
 */
public class MessService extends Service {
	private boolean isRun;// 线程是否继续的标志
	private Handler handler1; // 显示当前时间线程消息处理器。
	private Handler handler2;
	public static final String bm = "utf-8";
	private static JSONObject activeInfo;
	private boolean isaccept;
	private String replyip;
	private String currentname;
	private String location;// 我的位置
	private SQLiteDatabase db;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		//activemgr = new DbManager(this);
		 db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
		db.execSQL("CREATE TABLE IF NOT EXISTS activeinfo" +  
                "(activeid INTEGER PRIMARY KEY AUTOINCREMENT, activename VARCHAR,currentname VARCHAR,leader VARCHAE,parter VARCHAR,location VARCHAR,allip VARCHAR,activetime VARCHAR,leaderip VARCHAR)");
		isRun = true;
		final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// 注册通知管理器  
		// 向服务器传递坐标
		switch (Integer.parseInt(intent.getStringExtra("id"))) {
		case 1:
			location = "29.494749,106.576843";
			break;
		case 2:
			location = "29.495300,106.581111";
			break;
		case 3:
			location = "29.493586,106.581191";
			break;
		case 4:
			location = "29.496447,106.578065";
			break;
		}
		new Thread(new Runnable() {
			@Override
			// 在Runnable中，如果要让线程自己一直跑下去，必须自己定义while结构
			// 如果这个run()方法读完了，则整个线程自然死亡
			public void run() {
				// 定义一个线程中止标志

				try {

					ServerSocket serverSocket = new ServerSocket(20000);
					while (isRun) {
						Socket client = serverSocket.accept();
						BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), bm));
						String str = in.readLine();
						activeInfo = new JSONObject(str.split("？")[0]);
						replyip = activeInfo.getString("发起人ip：");
						currentname = str.split("？")[1];
//						Message msg = new Message();
//						handler1.sendMessage(msg);
						Activeinfo active=new Activeinfo(activeInfo.getString("活动名："),activeInfo.getString("参与者："), activeInfo.getString("活动时间"),activeInfo.getString("发起人："), activeInfo.getString("allip"), currentname, location,replyip);
						//activemgr.addactive(active);
						db.execSQL("INSERT INTO activeinfo (activename,currentname,leader,parter,location,allip,activetime,leaderip) VALUES( ?, ?, ?, ?, ?, ?, ?,?)", new Object[]{active.getActivename(),active.getCurrentname(),active.getLeader(),active.getParter(),active.getLocation(),active.getAllip(),active.getActivetime(),active.getLeaderip()});  
						Message msg2 = new Message();
						handler2.sendMessage(msg2);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();// 默认线程不启动，必须自己start()
		// 不停在接受线程的消息，根据消息的参数，进行处理 ，这里没有传递过来的参数
//		handler1 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
//			@Override
//			public boolean handleMessage(Message msg) {
//				 Builder builder = new Builder(getApplicationContext());
//				 try {
//				 builder.setTitle(
//				 "活动名：" + activeInfo.getString("活动名：") + ";" + "发起人：" +
//				 activeInfo.getString("发起人："));
//				 builder.setMessage("计划参与者：" +
//				 activeInfo.getString("参与者："));
//				 builder.setNeutralButton("不参与", new OnClickListener() {
//				
//				 @Override
//				 public void onClick(DialogInterface dialog, int which) {
//				 // TODO Auto-generated method stub
//				
//				 }
//				 });
//				 builder.setNegativeButton("参与", new OnClickListener() {
//				 @Override
//				 public void onClick(DialogInterface dialog, int which) {
//				 // TODO Auto-generated method stub
//				 new Thread() {
//				 public void run() {
//				 try {
//				
//				 Socket socket = null;
//				
//				 // 创建Socket
//				 socket = new Socket(replyip, 22222); // IP一定是本地机器的ip
//				 Map<String, String> replymap=new HashMap<String, String>();
//				 replymap.put("用户名", currentname);
//				 replymap.put("坐标", location);
//				 replymap.put("活动名",activeInfo.getString("活动名：") );
//				 replymap.put("参与者", activeInfo.getString("参与者："));
//				 replymap.put("allip", activeInfo.getString("allip"));
//				 JSONObject replyjson=new JSONObject(replymap);
//				 // 向服务器发送消息
//				 PrintWriter out = new PrintWriter(new BufferedWriter(
//				 new OutputStreamWriter(socket.getOutputStream(), bm)), true);
//				 out.println(replyjson.toString());
//				
//				 out.close(); 
//			                	 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), bm));
//			 					String str = reader.readLine();
//			 					JSONObject rjson=new JSONObject(str);
//			 						Activeinfo.activelist.add(new Activeinfo(rjson.getString("活动名：") , rjson.getString("参与者："), "2017.6.9"));
//			 					
//				 // 关闭Socket
//				 socket.close();
//				
//				 } catch (Exception e) {
//				 // TODO: handle exception
//				
//				 }
//				
//				 handler.sendEmptyMessage(0);// 执行完毕后给handler发送一个空消息
//				 }
//				
//				 // 定义Handler对象
//				 private Handler handler = new Handler() {
//				 @Override
//				 // 当有消息发送出来的时候就执行Handler的这个方法
//				 public void handleMessage(Message msg) {
//				 super.handleMessage(msg);
//				 // 处理UI
//				
//				 }
//				 };
//				 }.start();
//				 }
//				 });
//				 } catch (JSONException e) {
//				 // TODO Auto-generated catch block
//				 e.printStackTrace();
//				 }
//				 Dialog dialog=builder.create();
//				 dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//				 dialog.show();
//				return false;
//			}
//		});
		 handler2 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了  
             @SuppressWarnings("deprecation")  
             @Override  
             // 这里notification.setLatestEventInfo，  
             // 设置通知标题与内容会被eclipse标志过时，  
             // 但新的方法，使用builder去设置通知的方法只能应用于android3.0以上的设备，对于android2.2的设备是无法使用的。  
             // 在现时国内有部分设备还是在android2.2的情况下，还是用这条几乎兼容所有版本安卓的“过时”方法吧！  
             public boolean handleMessage(Message msg) {  

                 Notification notification = new Notification();  
                 notification.icon = R.drawable.ic_login;// 设置通知图标为app的图标  
                 notification.flags = Notification.FLAG_AUTO_CANCEL;// 点击通知打开引用程序之后通知自动消失  
                 notification.tickerText = "您有一条新消息";// 在用户没有拉开标题栏之前，在标题栏中显示的文字  
                 notification.when = System.currentTimeMillis();// 设置发送时间  
                 notification.defaults = Notification.DEFAULT_ALL;// 设置使用默认声音、震动、闪光灯  
                 // 以下三行：在安卓设备任意环境中中，如果点击信息则打开MainActivity  
                 Intent intent = new Intent(getApplicationContext(),  
                         PendActiveActivity.class);  
                 PendingIntent pendingIntent = PendingIntent  
                         .getActivity(getApplicationContext(), 0,  
                                 intent, 0);  
                 try {
					notification.setLatestEventInfo(  
					         getApplicationContext(), "提示：", "您收到"+activeInfo.getString("发起人：")+"发来的活动邀请！",pendingIntent);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
                                  
                       
                 notificationManager.notify(  
                         1, notification);// 要求通知管理器发送这条通知，其中第一个参数是通知在系统的id  
                 return false;  
             }  
         });  
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		isRun = false;

	}
}
